package com.youlai.rocketmq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author zc
 * @date 2022-10-27 00:56
 */
@Service
@Slf4j
public class BaseProducer {
    /**
     * 测试发送将参数topic定死，实际开发写入到配置文件
     */
    @Resource
    RocketMQTemplate rocketMQTemplate;

    /**
     * 同步消息
     */
    public boolean sync(String message) {
        boolean flag = true;
        String text1 = "发送消息:" + message;
        log.info(text1);
        SendResult sendResult1 = rocketMQTemplate.syncSend("base_topic", text1);
        log.info("同步响应:"+sendResult1.getSendStatus().toString());
        if(!SendStatus.SEND_OK.equals(sendResult1.getSendStatus())){
          flag = false;
        }
        return  flag;
    }

    /**
     * 异步消息
     */
    public boolean async(String message) {
        String text1 = "发送消息:" + message;
        log.info(text1);
        rocketMQTemplate.asyncSend("base_topic", text1 , new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("异步消息响应成功");
            }
            @Override
            public void onException(Throwable throwable) {
                log.info("异步消息响应发送失败");
            }
        });
        return true;
    }

    /**
     * 单向消息,不关心返回结果
     */
    public boolean oneWay(String message) {
        String text1 = "发送消息:" + message;
        log.info(text1);
        rocketMQTemplate.sendOneWay("base_topic", text1);
        log.info("单向发送-已发送...");
        return true;
    }

}
